//导入 uni-app-fetch 模块
import { createUniFetch } from "uni-app-fetch"
import { useUserStore } from "@/stores/user"
import { utils } from "../utils/utils"
//配置请求对象
const tabBarPagePaths = [
  'pages/task/index',
  'pages/message/index',
  'pages/my/index'
]
export const uniFeatch = createUniFetch({
  loading: { title: "正在加载中..." },
  baseURL: "https://slwl-api.itheima.net",
  intercept: {
    // 请求拦截器
    request(options) {
      const userStore = useUserStore()
      // 这里会自定义配置 可以在请求头上配置多个key
      const defaultHeaders = {
        Authorization: userStore.token
      }
      //options.header传递实参 因为后面方法的调用 会覆盖前面的默认请求头
      //如果不传实参就使用默认的token 
      options.header = Object.assign({}, defaultHeaders, options.header)
      return options
    },
    // 响应拦截器
    response(result) {
      if (result.statusCode === 401) {
        // console.log(result);
        // 获取当前页面栈
        const pageStack = getCurrentPages()
        const redirectURL = pageStack[pageStack.length - 1].route
        // console.log(redirectURL);
        const routeType = tabBarPagePaths.includes(redirectURL) ? "switchTab" : "redirectTo"
        uni.redirectTo({
          url: `/pages/login/index?redirectURL=/${redirectURL}&routeType=${routeType}`
        })
      }
      return result.data
    }
  }
})